package org.zn.mvcbase.mybatis.ddl;

import java.io.IOException;
import java.util.List;

import org.zn.commons.loader.PackageScanner;

import com.google.common.collect.Lists;

public class AutoTableCreater {

	/**
	 * [create,cover,drop,update]
	 */
	private String mode = "create";
	private String[] packages;
	private TableEntityProvider provider;
	private PackageScanner packageScanner;
	private Ddldao ddldao;

	private String defaultSchema;

	public String getMode() {
		return mode;
	}

	public void setMode(String mode) {
		this.mode = mode;
	}

	public String[] getPackages() {
		return packages;
	}

	public void setPackages(String[] packages) {
		this.packages = packages;
	}

	public TableEntityProvider getProvider() {
		return provider;
	}

	public void setProvider(TableEntityProvider provider) {
		this.provider = provider;
	}

	public PackageScanner getPackageScanner() {
		return packageScanner;
	}

	public void setPackageScanner(PackageScanner packageScanner) {
		this.packageScanner = packageScanner;
	}

	public Ddldao getDdldao() {
		return ddldao;
	}

	public void setDdldao(Ddldao ddldao) {
		this.ddldao = ddldao;
	}

	public String getDefaultSchema() {
		return defaultSchema;
	}

	public void setDefaultSchema(String defaultSchema) {
		this.defaultSchema = defaultSchema;
	}

	public void createrTable() throws IOException {

		PackageScanner scanner = new PackageScanner();

		List<String> classNameList = scanner.doScan(packages);

		List<TableEntity> tableEntitys = Lists.newArrayList();

		for (String name : classNameList) {
			tableEntitys.add(provider.provide(name));
		}

		if (mode.equals("create")) {

			createMode(tableEntitys);

		} else if (mode.equals("drop")) {

			dropMode(tableEntitys);

		}

	};
	
	

	private void createMode(List<TableEntity> tableEntitys) {

		for (TableEntity tableEntity : tableEntitys) {

			int flag = ddldao.hasTableflag(tableEntity.getSchema() == null ? defaultSchema : tableEntity.getSchema(),
					tableEntity.getTableName());

			if (flag == 0) {
				ddldao.createTable(tableEntity.getSchema(), tableEntity.getTableName(), tableEntity.getColumns(),
						tableEntity.getIds().get(0));
			}

		}

	}

	private void dropMode(List<TableEntity> tableEntitys) {

		for (TableEntity tableEntity : tableEntitys) {

			ddldao.dropTable(tableEntity.getSchema() == null ? defaultSchema : tableEntity.getSchema(),
					tableEntity.getTableName());
			ddldao.createTable(tableEntity.getSchema(), tableEntity.getTableName(), tableEntity.getColumns(),
					tableEntity.getIds().get(0));

		}

	}

}
